import XLSX from 'xlsx'

/// excel导入功能使用：
// 1、在需要的文件中引入importExcel.js文件
// 2、参数说明：file是指需要导入的excel文件
export function importexcel (file) {
  const types = file.name.split('.')[1]
  const fileType = ['xlsx', 'xlc', 'xlm', 'xls', 'xlt', 'xlw', 'csv'].some(item => item === types)
  if (!fileType) {
    this.$message('格式错误！请重新选择')
    return
  }

  return new Promise(function (resolve, reject) {
    const result = {}
    const fileName = file.name
    file2Xce(file).then(tabJson => {
      if (tabJson && tabJson.length > 0) {
        const dataArr = tabJson[0].sheet
        result.data = dataArr
        result.fileName = fileName
        resolve(result)
      }
    })
  })
}
function file2Xce (file) {
  return new Promise(function (resolve, reject) {
    const reader = new FileReader()
    reader.onload = function (e) {
      const data = e.target.result
      this.wb = XLSX.read(data, {
        type: 'binary',
        codepage: 936 // taobao订单CSV文件是GB2312编码，需指定中文编码，否则乱码
      })
      const result = []
      this.wb.SheetNames.forEach((sheetName) => {
        result.push({
          sheetName: sheetName,
          sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName])
        })
      })
      resolve(result)
    }
    reader.readAsBinaryString(file)
  })
}
